const http = require('node:http')
const url = require('node:url')
const fs = require('node:fs')
const {createProxyMiddleware} = require('http-proxy-middleware')
const html = fs.readFileSync('./index.html')
const config = require('./jueyi.config.js')

http.createServer((req, res)=>{
/*    const {pathname, query} = url.parse(req.url, true)
    if(req.method === 'POST'){
        if(pathname === '/login'){
            let data = ''
            req.on('data', (chunk)=>{
                data += chunk
            })
            req.on('end',()=>{
                res.setHeader('Content-Type', "application/json")
                res.statusCode = 200
                res.end(data)
            })
        }
        else {
            res.statusCode = 404
            res.end('404')
        }
    }
    else if (req.method === 'GET'){
        if(pathname === '/get'){
            console.log(query)
            res.end('GET')
        }
        else {
            res.statusCode = 404
            res.end('404')
        }
    }*/

    // 反向代理
    const {pathname} = url.parse(req.url, true)
    const proxyList = Object.keys(config.serve.proxy)
    if(proxyList.includes(pathname)){
        const proxy = createProxyMiddleware(config.serve.proxy[pathname])
        proxy(req, res)
        return
    }
    res.writeHead(200, {
        'Content-Type': 'text/html'
    })
    res.end(html)
}).listen(80, ()=>{
    console.log('启动成功，端口号80')
})